import axios from 'axios'
import { ElNotification } from 'element-plus';

window.debug = false;

let apiU = window.location.href
apiU = 'http://'+apiU.match(/(?<=\/\/).*(?=:)/g)[0]+':8888/'

const instance = axios.create({
  //baseURL: 'http://localhost:8888/',
  baseURL: apiU,
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    // 发送请求前可以在此处理，比如添加Token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}` // 添加token到请求头
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response
  },
  error => {
    let message = ''
    if (error.response) {
      switch (error.response.status) {
        case 400:
          message = '请求错误 (400)'
          break
        case 401:
          message = '未授权，请登录正确的权限账户 (401)'
          break
        case 403:
          message = '拒绝访问 (403)'
          break
        case 404:
          message = '请求地址出错 (404)'
          break
        case 500:
          message = '服务器内部错误 (500)'
          break
        default:
          message = `连接出错 (${error.response.status})`
      }
    } else if (error.request) {
      message = '请求失败，请检查网络连接'
    } else {
      message = `请求出错: ${error.message}`
    }
    console.log(message)
    // 在此统一显示错误提示，可以使用 alert 或者自定义提示组件
    if (typeof ElNotification !== 'undefined') {
      ElNotification({
        title: '提示',
        message: message,
        type: 'warning',
        duration: 3000
      });
    } else {
      alert(message)
    }

    return Promise.resolve()
  }
)


//获取设备
export const getConfig = async () => {
  try {
    const response = await instance.get('/item')
    if(response.data){
      return response.data
    }else{
      throw response.data
    }

  } catch (error) {
    console.log(error)
  }
}

//获取设备
export const getItemById = async (id) => {
  try {
    const response = await instance.get(`/item/${id}`)
    if(response.data){
      return response.data
    }else{
      throw response.data
    }

  } catch (error) {
    console.log(error)
  }
}

export const upItemById = async (id , item, password) => {
  try {
    const res = await instance.put(`/item0xdf/${id}?pwd=${password}`, item);
    // 检查 response.data 是否有值
    if (res.data) {
      return res.data;  // 返回具体的返回数据
    } else {
      throw new Error("No response data");
    }
  } catch (error) {
    console.log(error)
    return error
  }
}


export const addItem = async (item, password) => {
  try {
    const response =  await instance.post(`/item0xdf?pwd=${password}`,item);
    if(response.data){
      return response.data
    }else{
      throw response.data
    }
  } catch (error) {
    console.log(error)
    return error
  }
}


//判断是否手机访问
export  const  isMobile = ()=> {
  const userAgent = navigator.userAgent || navigator.vendor || window.opera;
  return /mobile|Mobile|Android|android|iPad|iPhone|iPod/.test(userAgent) && !window.MSStream;
}

export default instance
